package com.guigu.work.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.base.entity.CoreOrg;
import com.guigu.base.entity.dto.TransportTripsDto;
import com.guigu.base.entity.dto.TruckDto;
import com.guigu.base.entity.vo.TruckStatusDashboardVO;
import com.guigu.common.enums.transporttask.TransportTaskAssignedStatus;
import com.guigu.common.enums.transporttask.TransportTaskLoadingStatus;
import com.guigu.common.enums.transporttask.TransportTaskStatus;
import com.guigu.work.dto.TaskTransportDTO;
import com.guigu.work.dto.TransportOrderDTO;
import com.guigu.work.entity.DriverJob;
import com.guigu.work.entity.TaskTransport;
import com.guigu.work.entity.TransportOrder;
import com.guigu.work.entity.TransportOrderTask;
import com.guigu.work.entity.vo.TaskTransportDetailsVO;
import com.guigu.work.entity.vo.TransportOrderVO;
import com.guigu.work.feign.BaseFeign;
import com.guigu.work.feign.OrderFeign;
import com.guigu.work.mapper.TaskTransportMapper;
import com.guigu.work.service.DriverJobService;
import com.guigu.work.service.TaskTransportService;
import com.guigu.work.service.TransportOrderService;
import com.guigu.work.service.TransportOrderTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 运输任务表 服务实现类
 * </p>
 *
 * @author liAo
 * @since 2021-11-09
 */
@Transactional
@Service
@Slf4j
public class TaskTransportServiceImpl extends ServiceImpl<TaskTransportMapper, TaskTransport> implements TaskTransportService {
    @Autowired(required = false)
    private TaskTransportMapper mapper;
    @Autowired
    private TransportOrderTaskService totService;
    @Autowired
    private TransportOrderTaskService transportOrderTaskService;

    @Autowired
    private DriverJobService driverJobService;
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private TransportOrderService transportOrderService;
    @Autowired
    private BaseFeign baseFeign;

    /**
     * 新增运输任务
     *
     * @param dto 运输任务信息
     * @return 运输任务信息
     */
    @Override
    public TaskTransport saveTaskTransport(TaskTransportDTO dto) {
        if (null == dto) {
            throw new IllegalArgumentException("参数异常!");
        }

        /**
         * 删除之前的运输任务,根据运单集合查询出对应的运输任务,将其删除
         */
        if (CollUtil.isNotEmpty(dto.getTransportOrderIds())) {
            String transportOrderId = dto.getTransportOrderIds().get(0);
            if (StringUtils.isNotBlank(transportOrderId)) {
                QueryWrapper<TransportOrderTask> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("transport_order_id", transportOrderId);
                TransportOrderTask task = transportOrderTaskService.getOne(queryWrapper);
                if (ObjectUtils.isNotEmpty(task)) {
                    this.baseMapper.deleteById(task.getTransportTaskId());

                    log.info("删除之前的运输任务成功!");
                    /**
                     * 在删除之前的运输任务和运单ID关联的数据
                     */
                    dto.getTransportOrderIds().stream().forEach(s -> {
                        totService.deleteBytoIdOrttId(s, task.getTransportTaskId());
                    });
                    log.info("在删除之前的运输任务和运单ID关联的数据成功!");
                    /**
                     * 删除之前的司机作业单
                     */
                    QueryWrapper<DriverJob> query = new QueryWrapper<>();
                    query.eq("task_transport_id", task.getTransportTaskId());
                    driverJobService.remove(query);
                    log.info("删除司机作业单成功!");
                }
                /**
                 * 更改之前的运单状态
                 */
                TransportOrder transportOrder = new TransportOrderDTO();
                transportOrder.setId(transportOrderId);
                /**
                 * 已装车
                 */
                transportOrder.setStatus(2);
                /**
                 * 已调度
                 */
                transportOrder.setSchedulingStatus(3);
                /**
                 * 修改运单状态
                 */
                transportOrderService.updateById(transportOrder);
            }
        }
        //status
        dto.setStatus(TransportTaskStatus.PENDING.getCode());
        //assigned_status
        dto.setAssignedStatus(TransportTaskAssignedStatus.TO_BE_DISTRIBUTED.getCode());
        //loading_status
        dto.setLoadingStatus(TransportTaskLoadingStatus.EMPTY.getCode());
        //create_time
        dto.setCreateTime(new Date());

        this.saveOrUpdate(dto);
        return dto;
    }

    /**
     * 获取运输任务分页数据
     *
     * @param dto
     * @return 运输任务分页数据
     */
    @Override
    public IPage<TaskTransport> findByPage(TaskTransportDTO dto) {
        if (null == dto) {
            throw new IllegalArgumentException("参数异常!");
        }
        Page<TaskTransport> page = new Page<>(dto.getPage(), dto.getPageSize());
        LambdaQueryWrapper<TaskTransport> wrapper = new LambdaQueryWrapper<>();
        //任务id
        if (StringUtils.isNotBlank(dto.getId())) {
            wrapper.eq(TaskTransport::getId, dto.getId());
        }
        //运输任务状态
        if (null != dto.getStatus() && dto.getStatus() > 0) {
            wrapper.eq(TaskTransport::getStatus, dto.getStatus());
        }

        return this.page(page, wrapper);
    }

    /**
     * 获取运输任务列表
     *
     * @param dto
     * @return 运输任务列表
     */
    @Override
    public List<TaskTransport> findAll(TaskTransportDTO dto) {
        if (null == dto) {
            throw new IllegalArgumentException("参数异常!");
        }
        LambdaQueryWrapper<TaskTransport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getIds() != null && dto.getIds().size() > 0) {
            lambdaQueryWrapper.in(TaskTransport::getId, dto.getIds());
        }
        if (StringUtils.isNotEmpty(dto.getId())) {
            lambdaQueryWrapper.like(TaskTransport::getId, dto.getId());
        }
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(TaskTransport::getStatus, dto.getStatus());
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(dto.getTruckId()), TaskTransport::getTruckId, dto.getTruckId());

        return this.list(lambdaQueryWrapper);
    }

    /**
     * 根据运输任务id查询详情
     *
     * @param id
     * @return
     */
    @Override
    public TaskTransportDetailsVO findTransportDetailsById(String id) {
        /**
         * 获取运输任务对象
         */
        TaskTransport taskTransport = this.baseMapper.selectById(id);

        /**
         * 根据车辆Id查询司机id,再来根据司机Id来获取司机工作对象和司机名称
         */


        /**
         *
         * 获取车辆对象
         */
        TruckDto truckDto = baseFeign.findTruckById(taskTransport.getTruckId()).getData();


        /**
         * 获取起始机构
         */
        CoreOrg startCoreOrg = baseFeign.findCoreOrgById(taskTransport.getStartAgencyId()).getData();
        /**
         * 获取结束结构
         */
        CoreOrg endCoreOrg = baseFeign.findCoreOrgById(taskTransport.getEndAgencyId()).getData();
        /**
         * 获取车次对象
         */
        TransportTripsDto transportTripsDto = baseFeign.fineTripsById(taskTransport.getTransportTripsId()).getData();

        /**
         * 获得运单列表
         */
        QueryWrapper<TransportOrderTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("transport_task_id", taskTransport.getId());
        List<TransportOrderTask> transportOrderTaskList = transportOrderTaskService.list(queryWrapper);

        /**
         * 运单列表
         */
        List<TransportOrderVO> list = transportOrderTaskList.stream().map(t -> {
            TransportOrderVO transportOrderVO = new TransportOrderVO();
            TransportOrder transportOrder = transportOrderService.getById(t.getTransportOrderId());
            BeanUtil.copyProperties(transportOrder, transportOrderVO);
            Map map = orderFeign.getOrderInfoByOrderId(transportOrder.getOrderId()).getData();
            transportOrderVO.setOrder(map);
            return transportOrderVO;
        }).collect(Collectors.toList());

        /**
         * 开始赋值
         */
        TaskTransportDetailsVO taskTransportDetailsVO = new TaskTransportDetailsVO();
        BeanUtil.copyProperties(taskTransport, taskTransportDetailsVO);
        /**
         * 设置起点机构
         */
        taskTransportDetailsVO.setStartAgency(startCoreOrg);
        /**
         * 设置结束机构
         */
        taskTransportDetailsVO.setEndAgency(endCoreOrg);

        taskTransportDetailsVO.setStartAgencyName(startCoreOrg.getName());
        taskTransportDetailsVO.setEndAgencyName(endCoreOrg.getName());
        taskTransportDetailsVO.setTruckName(truckDto.getBrand());
        taskTransportDetailsVO.setTransportTripsName(transportTripsDto.getName());
        /**
         * 设置运单信息
         */
        taskTransportDetailsVO.setTransportOrderList(list);
        /**
         * 设置车辆 信息
         */
        taskTransportDetailsVO.setTruckDto(truckDto);
        return taskTransportDetailsVO;
    }

    @Override
    public TruckStatusDashboardVO getTruckStatusCount() {
        TruckStatusDashboardVO truckStatusDashboardVO = new TruckStatusDashboardVO();
        List<Integer> list = new ArrayList<>();
        List<String> list1 = new ArrayList<>();

        /**
         * 空载
         */
        QueryWrapper<TaskTransport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("loading_status", 1);
        list1.add("半载");
        list.add(count(queryWrapper));


        /**
         * 半载状态
         */
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("loading_status", 2);
        list.add(count(queryWrapper));
        list1.add("满载");

        /***
         * 满载状态
         */
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("loading_status", 3);
        list.add(count(queryWrapper));
        list1.add("空载");
        truckStatusDashboardVO.setTruckStatusCount(list);
        truckStatusDashboardVO.setTruckStatusName(list1);
        return truckStatusDashboardVO;
    }
}
